package com.lge.clock; 
   
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/* LGSI_CHANGE_S: Alarm
 * 2012.04.13,prajna.dalei@lge.com,
 * Number conversion in Alarm settings
 */
import java.util.Locale;
/* LGSI_CHANGE_E: Alarm*/

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.SimpleCursorAdapter.CursorToStringConverter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.clock.alarmclock.ALProvider;
import com.lge.clock.alarmclock.AlarmAlert;
import com.lge.clock.alarmclock.AlarmConstants;
import com.lge.clock.alarmclock.AlarmDeleteListActivity;
import com.lge.clock.alarmclock.AlarmMeta;
import com.lge.clock.alarmclock.Alarms;
import com.lge.clock.alarmclock.SettingsActivity;
import com.lge.clock.alarmclock.ToastMaster;
/* LGSI_CHANGE_S: Arabic and Farsi number conversion support.
 * 15/02/12 pradeep.gk@lge.com
 * To support arabic and farsi number conversion support.
 */
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.MediaInfoHolder;

/* LGSI_CHANGE_E: Arabic and Farsi number conversion support */
import com.lge.clock.util.Log;
import com.lge.clock.util.CommonUtil.AlarmDBQueryCondition;
import com.lge.clock.util.CommonUtil.OPERATOR;
/*[START] 2012.02.16 suein1209.kim gesture sensor*/
import android.hardware.LGSensor;
/*[END] 2012.02.16 suein1209.kim gesture sensor*/

/**
 * @author LGE Cappuccino
 */
public class AlarmFragment extends Fragment implements AlarmConstants {
	private LayoutInflater mFactory;
	private ListView list;
	private Menu m_menu;
	private int listCount = 0;

	private static final String TAG = "AlarmFragment";
	///////////////////////////////////////////////////////////////////////////////////////////////////
	private Map<String, String> storageOnOffMaps;
	private Map<String, String> storageCheckMaps;
	
	private static String save_id = "";
	private static String last_save_id = "";		// hjcheong@lge.com alarm id of last saved.
	private int scrollIndex = 0;		// hjcheong@lge.com input the position value to setSelectionFromTop 
	
	private static final int NEW_ID = R.id.new_alarm_menu;
	private static final int DELETEALL_ID = R.id.deletall_menu;
	private static final int MULTISELECT_ID = R.id.delete_alarm_menu;
	private static final int SETTINGS_ID = R.id.alarm_setting_menu;
	///////////////////////////////////////////////////////////////////////////
	private Cursor cursorQuery;
	private static Context mContext = null;
	private ContentResolver resolver;
	
	private static final int MAX_ITEM_CNT = 15;
	
	private static final int INITIAL_BUFF_SIZE = 30;
	
	// 20101019_mhkwon_Block multi touch [[
	// private static boolean BlockMultiTouchFlag = false;
	// 20101019_mhkwon_Block multi touch ]]
	
	private Map<String, String> storageWidgetYNMaps;
	private boolean stateYN = false;
	
	//added by essin@lge.com
	private MediaPlayer mplayer ; // 20101104_mhkwon_QG15889_Touch_tone 
    private AudioManager mAudioManager = null;
    
//    private static boolean mShowDivider = false;
//	//sunghun.an@lge.com Common : Gesture Guide Pop up  [START]
//	private boolean mGestureGuide = false;
//	private AlertDialog gestureGuideDlg =null;
//	private AnimationDrawable mAnimation;
//	private CheckBox check = null;
//	private SharedPreferences pref;
//	//sunghun.an@lge.com Common : Gesture Guide Pop up  [END]	
    
    public static String getSaveID() {
    	return save_id;
    }
    
    public static Context getContext() {
    	return mContext;
    }
    
    // added by essin@lge.com
	// 20101104_mhkwon_QG15889_Touch_tone  [[
    /**
     * Field playTouchToneThread.
     */
    Runnable playTouchToneThread = new Runnable() {
        public void run() {
            int getRingerMode = 0;
            final String modeRinger = "mode_ringer";

            if(mAudioManager == null){
                ContentResolver mContentResolver = getActivity().getContentResolver();
                mAudioManager = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);
                getRingerMode = Settings.System.getInt(mContentResolver, modeRinger, AudioManager.RINGER_MODE_NORMAL);
            }
            else {
                getRingerMode = mAudioManager.getRingerMode();
            }

            if (Settings.System.getInt(resolver, Settings.System.SOUND_EFFECTS_ENABLED, 0) == 1
            			&& getRingerMode == AudioManager.RINGER_MODE_NORMAL ) {
            	mAudioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
            }
        };
    };
    
    Handler mTouchSoundHandler = new Handler();
    
    // 20101104_mhkwon_QG15889_Touch_tone  ]]
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
    	View main_view = inflater.inflate(R.layout.alarm_main_list, container ,false);
    	
    	list = (ListView)main_view.findViewById(R.id.alarms_list);
		if ( list != null ){
			registerForContextMenu(list);
		}
		
		
		
        if ( list != null ) {
            
            AdapterView.OnItemClickListener listItemClickListener = new AdapterView.OnItemClickListener() {
                
                public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
                    final String strID = Long.toString(id);
                    modify_ALSettings(strID);
                }
            };
            
            list.setOnItemClickListener(listItemClickListener);
        }

	    mFactory = inflater;
		return main_view;
	}
    
    
    
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);
		
	}

	
	/**
	 * Field setNextAlertThread.
	 */
	Runnable setNextAlertThread = new Runnable() {
	    public void run() {
	    	
	    	if(mContext == null){
	    		mContext = getActivity();
	    	} //End of if
	    	
	    	Alarms.disableExpiredAlarms(mContext, true);
    		Alarms.setNextAlert(mContext);
	    	
	    };
	};
	
// 20100827_mhkwon_SE6988_Save selected list item when resume. [[
    /**
     * Method onSaveInstanceState.
     * @param state Bundle
     */
    @Override
    public void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        Log.d(TAG, "onSaveInstanceState(Bundle state)");      
    }
             
	/**
	 * Method onResumeFunc.
	 */
	public void onResumeFunc() {
		onResume();
	}
	
	/**
	 * Method onResume.
	 */
	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
		/*[START] 2012.01.16 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #121774, 121810*/
		avoidRedundantSetAlarmClick = true;
		/*[END] 2012.01.16 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #121774, 121810*/
		list_func("TOTAL");
	}
	 
	/**
	 * when listview is show, option is different.
	 * when not deleted. ==> gubun = "TOTAL"
	 * @param gubun
	 */
	
    private void list_func(String gubun) { 
    	Log.d(TAG, "gubun ---->" + gubun);
    	scrollIndex = 0;
    	
    	// 20100827_mhkwon_SE6988_Save selected list item when resume. [[
        boolean bNew_stroagecheck_flag = false;
		storageOnOffMaps = new HashMap<String, String>();
		
		if (storageCheckMaps == null) {
		    storageCheckMaps = new HashMap<String, String>();
		    bNew_stroagecheck_flag = true;
		}
		// 20100827_mhkwon_SE6988_Save selected list item when resume. ]]
		
		storageWidgetYNMaps = new HashMap<String, String>();
		
		if( cursorQuery != null) {
			cursorQuery.close();
		}
		
		if ("TOTAL".equalsIgnoreCase(gubun)) {
			cursorQuery = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION_1_STRINGS, null, null, "widget_yn desc, hour, minutes, _id");
			// cursorQuery management function : close() is not need.
			//startManagingCursor(cursorQuery);
			//cursorQuery = getActivity().managedQuery(Uri.parse(Alarms.CONTENT_ALARMS_URI_STRING.concat("?queryType=1")), PROJECTION_1_STRINGS, null, null, "widget_yn desc, hour, minutes, _id");
		} 
		else {
			/*if(cursorQuery != null) {
				cursorQuery.close();
			}*/
			cursorQuery = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION_1_STRINGS, "widget_yn = 'N'", null, "hour, minutes, _id");
			//cursorQuery = getActivity().managedQuery(Uri.parse(Alarms.CONTENT_ALARMS_URI_STRING.concat("?queryType=1")), PROJECTION_1_STRINGS, "widget_yn = 'N'", null, "hour, minutes, _id");
			
			// cursorQuery management function : close() is not need.
			//startManagingCursor(cursorQuery); 
		}
		if(cursorQuery != null){
			listCount = cursorQuery.getCount();
		}
		
		//BASICPKG_S AlarmClock [sungtan.back@lge.com 110309] New alarm layout ?브쑬??
		View view = getView();
		if(view != null){
			View titleView = view.findViewById(R.id.noTitleTop);
			if( listCount == 0 ) {
				setViewVisible(titleView, true);
			} else {
				setViewVisible(titleView, false);
			}
		}
		//BASICPKG_E AlarmClock

		setOptionMenuStatus();  

		String strID = "";
		int indexofScroll = 0; // hjcheong@lge.com order to saved cursor
		if ( cursorQuery != null && cursorQuery.moveToFirst() ) {
			do {
				strID = cursorQuery.getString(0);
				Log.i(TAG, "cursorQuery.getString(0)" + strID);
				if (cursorQuery.isFirst()) {
					Log.i(TAG, "cursorQuery.isFirst() : " + strID);
				}
				if ( last_save_id.equals(strID) ) {
					scrollIndex = indexofScroll;
					Log.i(TAG, "scrollIndex : " + scrollIndex + ", last_save_id : " + last_save_id);
				}
				storageOnOffMaps.put( strID, cursorQuery.getString(4));
				  
				// 20100827_mhkwon_SE6988_Save selected list item when resume. [[
				if (bNew_stroagecheck_flag == true) {
					storageCheckMaps.put( strID, "0" );
				}
				// 20100827_mhkwon_SE6988_Save selected list item when resume. ]]
				  
				if ("Y".equalsIgnoreCase( cursorQuery.getString(5) )) {
					storageWidgetYNMaps.put( strID, "Y" );
				} else if ("N".equalsIgnoreCase( cursorQuery.getString(5) )) {
					storageWidgetYNMaps.put( strID, "N" );
				}
				indexofScroll++;
			} while( cursorQuery.moveToNext() );
		}
		 
		String[] fromStrs = new String[] { };
		int[] toInts = new int[] { };
		if(cursorQuery != null) {		
		list.setAdapter(new AlarmListCursorAdapter(this, R.layout.alarm_main_listitem, cursorQuery, fromStrs, toInts));
		}
		list.setSelectionFromTop(scrollIndex, 0);

    } ////////////////////////////////////////////////////////////////////////////
    
    private void setViewVisible(View view, boolean bShow){
    	if ( view != null ){
    		int visible = bShow ? View.VISIBLE : View.GONE;
        	view.setVisibility(visible);
    	}
    }
    //BASICPKG_E AlarmClock
    
    /**
     *  port/land ... set VISIBLE/GONE
     * @param newConfig Configuration
     * @see android.content.ComponentCallbacks#onConfigurationChanged(Configuration)
     */
    @Override
	 public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
	    
		switch(newConfig.orientation){
			case Configuration.ORIENTATION_LANDSCAPE:
				stateYN = true;
				if (listCount == 0) {
					((LinearLayout)getView().findViewById(R.id.noTitleTop)).setVisibility(View.VISIBLE);
		        } else {
		        	((LinearLayout)getView().findViewById(R.id.noTitleTop)).setVisibility(View.GONE);
		        }
		   		break;

			case Configuration.ORIENTATION_PORTRAIT:
				stateYN = false;
		        if (listCount == 0) {
		        	((LinearLayout)getView().findViewById(R.id.noTitleTop)).setVisibility(View.VISIBLE);
		        } else {
		        	((LinearLayout)getView().findViewById(R.id.noTitleTop)).setVisibility(View.GONE);
		        }
				break;
				
			default:
				break;
		}
    }
	
    /**
     *          menu
     * @param menu Menu
     * @return boolean
     */
	@Override     
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.alarm_menu, menu);
		m_menu = menu; 
		setOptionMenuStatus(); 
		
	}

 
	public void setOptionMenuStatus() {
		Log.e(TAG, " setOptionMenuStatus() listCount : "+listCount);
		MenuItem item;
		if(m_menu != null){
			item = m_menu.findItem(R.id.new_alarm_menu);
			if(item != null) 	
				item.setEnabled(listCount < MAX_ITEM_CNT);
			
			item = m_menu.findItem(R.id.delete_alarm_menu);
			if(item != null) 	
				item.setVisible(listCount>0);
			
			item = m_menu.findItem(R.id.deletall_menu);
			if(item != null)	
				item.setVisible(listCount>0);			
		}
	}
 
	/**
	 * Method onOptionsItemSelected.
	 * @param item MenuItem
	 * @return boolean
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return ( canMenuChoice(item) || super.onOptionsItemSelected(item) );
	}
	
	/**
	 * 2012.01.16 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #121774, 121810 
	 */
	private static boolean avoidRedundantSetAlarmClick = true; 
	/**
	 * menu event - [clock / selectall / deselectall / delete / setting ] 
	 * @param item
	 * @return
	 */
	private boolean canMenuChoice(MenuItem item) {
		Map.Entry<String, String>temp;
        Set sets;
        Iterator ii;
           
		switch (item.getItemId()) {
			case NEW_ID:
				/*[START] 2012.01.16 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #121774, 121810*/
				if(avoidRedundantSetAlarmClick){
					setAlarm("INSERT");
					avoidRedundantSetAlarmClick = false;
				} //End Of if
				/*[END] 2012.01.16 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #121774, 121810*/
				
				return true;
				
			case DELETEALL_ID:
				storageCheckMaps.clear();
                storageCheckMaps = null; 
				list_func("OK");
				
				if ( storageCheckMaps != null ) {
					sets = storageCheckMaps.entrySet();
		            ii   = sets.iterator();
		             
		            while(ii.hasNext()) {
		            	temp = (Map.Entry<String, String>) ii.next();
		                storageCheckMaps.put((String)temp.getKey(), "1");
		                Log.d(TAG, ii.toString());
		            }
		              
		            deleteAllYN();
				}
				return true;
			          	           
			case MULTISELECT_ID:
				if (listCount == 1 && cursorQuery != null) {	
					cursorQuery.moveToFirst();
					confirmDeleteDialog(cursorQuery.getInt(0));
				} else {
					Intent mIntent = new Intent(getActivity(),
							AlarmDeleteListActivity.class);
					startActivity(mIntent);
				}
				return true;
				    
			case SETTINGS_ID :   
				startActivity(new Intent(getActivity(), SettingsActivity.class));       
				return true;
				
			default :
				return false;
		}
	}
        
	/**
	 * Method defaultRingtone.
	 * @return String
	 */
	public String defaultRingtone() {
		String defaulttone = "";
	    Uri alert = RingtoneManager.getActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_ALARM);
	    
	    if (alert == null) {
        	return "Off";
	    } else { 
	    	if ((alert.toString()).indexOf("content://media/external") >= 0) {  
	    		final String[] external_Columns = new String[] {
              	   	     android.provider.BaseColumns._ID, 
              	   	     android.provider.MediaStore.MediaColumns.TITLE,
              	   	     "\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\"",
              	   	     android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
         	   	};
   				         
         	    Cursor cur = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, external_Columns,
         	    							  null,  null, "_id");
         	    if (cur == null) {
	         	    int i = 1;
			        boolean tag = false;
			        
			        Cursor cc = null;
			        try {
			        	cc = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
		               			"is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
						if ( cc != null && cc.moveToFirst() ) {
							do {
								// Get the field values     
								Uri uri1 = ContentUris.withAppendedId(Uri.parse(cc.getString(2)), cc.getLong(0));
								if (uri1.toString().equalsIgnoreCase(alert.toString())) {
									Settings.System.putString(resolver, Settings.System.ALARM_ALERT, uri1.toString()); 
									defaulttone = uri1.toString();
									tag = true;
									 
									return defaulttone;
								}
								     
								if (i == 4) {
									defaulttone = uri1.toString();
								}
								i++;
							} while ( cc.moveToNext() );
						}
			        } catch (Exception e) {
			        	e.printStackTrace();
			        } finally {
			        	if ( cc != null )
			        		cc.close();
			        }
				    
			    	if (tag == false) { 
			    		Settings.System.putString(resolver, Settings.System.ALARM_ALERT, defaulttone ); 
			    		return defaulttone;
			    	}   
         	    } else {
         	    	try {
         	    		if ( cur != null && cur.moveToFirst() ){
    	         	   		do {
    	     	    	       	Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
    	     	    	       	if (uri1.toString().equalsIgnoreCase(alert.toString()) ) {
    	     	    	       		return alert.toString();
    		  	    	       	}
    	     	    	    } while (cur.moveToNext());
    	         	   	}
         	    	} catch (Exception e) {
         	    		e.printStackTrace();
         	    	} finally {
         	    		if ( cur != null )
         	    			cur.close();
         	    	}
         	    }    
	    	} else if ((alert.toString()).indexOf("content://media/internal") >= 0) { 
			    int i = 1;
		        boolean tag = false;
		        
		        Cursor cur = null;
		        try {
		        	cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
			               	"is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
					if ( cur != null && cur.moveToFirst() ) {
						do {
							// Get the field values     
							Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
							if (uri1.toString().equalsIgnoreCase(alert.toString())) {
								Settings.System.putString(resolver, Settings.System.ALARM_ALERT, uri1.toString());
							    defaulttone = uri1.toString();
							    tag = true;
							    break;
							}
							if (i == 4) {
								defaulttone = uri1.toString();
							}
							i++;
						} while (cur.moveToNext());
					}
		        } catch (Exception e) {
		        	e.printStackTrace();
		        } finally {
		        	if ( cur != null )
		        		cur.close();
		        }

		        if (tag == false) {
		    		Settings.System.putString(resolver, Settings.System.ALARM_ALERT, defaulttone); 
		    	}
	    	}
	    }
	    
	    return defaulttone;   
	}
       
	/**
	 * Method update.
	 * @param id String
	 * @param value String
	 * @param hour int
	 * @param minutes int
	 * @param daysOfWeek Alarms.DaysOfWeek
	 */
	public void update(String id, String value, final int hour, final int minutes, final Alarms.DaysOfWeek daysOfWeek) {
		boolean isChecked = false;
		if ( "1".equals(value) ) {
			isChecked = true;
		}
		
		synchronized ( this ) {
			try {
				Alarms.enableAlarm(getActivity(), Integer.parseInt(id), isChecked);
			} catch ( NumberFormatException e ) {
				e.printStackTrace();
			}
		}
		
		if (isChecked) {
			// changed by essin@.lge.com 2010.1.29
			Handler calcueHandler = new Handler();
			Runnable calcueHandlerThread = new Runnable() {
				public void run() {
					long timeInMillis = calculateAlarm(hour, minutes, daysOfWeek).getTimeInMillis();
					String toastText = formatToast(timeInMillis);
			        Toast toast = Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT);
			        toast.show();
				}
			};
			calcueHandler.postDelayed(calcueHandlerThread, 0);
        }
	}
	
	private Calendar calculateAlarm(int hour, int minute, Alarms.DaysOfWeek aaa) {
        // start with now
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());

        int nowHour = c.get(Calendar.HOUR_OF_DAY);
        int nowMinute = c.get(Calendar.MINUTE);

        // if alarm is behind current time, advance one day
        if (hour < nowHour  ||
            hour == nowHour && minute <= nowMinute) {
            c.add(Calendar.DAY_OF_YEAR, 1);
        }
        
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        int addDays = aaa.getNextAlarm(c);
        if (addDays > 0) {
        	c.add(Calendar.DAY_OF_WEEK, addDays);
        }
        
        return c;
    }
	
	private static final int ONE_SEC = 1000;
	private static final int ONE_MIN = ONE_SEC * 60;
	private static final int ONE_HOUR = ONE_MIN * 60;
	private static final int SIXTY_MIN = 60;
	private static final int ONE_DAY_HOUR = 24;
	
	/**
     * format "Alarm set for 2 days 7 hours and 53 minutes from
     * now"
     */
    private String formatToast(long timeInMillis) {
        long delta = timeInMillis - System.currentTimeMillis();
        long hours = delta / ONE_HOUR;
        long minutes = delta / ONE_MIN % SIXTY_MIN;
        long days = hours / ONE_DAY_HOUR;
        hours = hours % ONE_DAY_HOUR;

        String daySeq = (days == 0) ? "" :
                (days == 1) ? getString(R.string.day) :
                getString(R.string.days, Long.toString(days));

        String minSeq = (minutes == 0) ? "" :
                (minutes == 1) ? getString(R.string.minute) :
                getString(R.string.minutes, Long.toString(minutes));

        String hourSeq = (hours == 0) ? "" :
                (hours == 1) ? getString(R.string.STR_Clock_HOUR_SHORT) :
                getString(R.string.hours, Long.toString(hours));

        boolean dispDays = days > 0;
        boolean dispHour = hours > 0;
        boolean dispMinute = minutes > 0;
        
        final int nDispDays = 1;
        final int nDispHour = 2;
        final int nDispMin  = 4;

        int index = (dispDays ? nDispDays : 0) |
                    (dispHour ? nDispHour : 0) |
                    (dispMinute ? nDispMin : 0);

        String[] formats = getResources().getStringArray(R.array.alarm_set);
 /* LGSI_CHANGE_S: Alarm
 * 2012.04.13,prajna.dalei@lge.com,
 * Number conversion in Alarm settings
 */       
        if("ar".equals(Locale.getDefault().getLanguage()) || "fa".equals(Locale.getDefault().getLanguage()))
			{
			return String.format(formats[index], CommonUtil.convertArabFarsiNum(daySeq,false), CommonUtil.convertArabFarsiNum(hourSeq,false), CommonUtil.convertArabFarsiNum(minSeq,false));
			}
		else 
			{			
        return String.format(formats[index], daySeq, hourSeq, minSeq);
			}
 /* LGSI_CHANGE_E: Alarm*/
    }
    
	/**
	 * when select is deleteall or some delete, that occur popup
	 */
	public void deleteAllYN() {
		Map.Entry<String, String>temp;
		Set sets;
		Iterator ii ;   
		sets = storageCheckMaps.entrySet();
		ii   = sets.iterator();
		Log.d(TAG, Integer.toString(sets.size()));
		int nDeleteCountYN = 0;

		while(ii.hasNext()) {
			temp = (Map.Entry<String, String>) ii.next();
     	
			if ("1".equals(temp.getValue())) {
				nDeleteCountYN++;
			}
		}
    
		Log.d(TAG, "===DeleteCountYN : " + nDeleteCountYN + " / listCount : " + listCount );
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		if (nDeleteCountYN == listCount ) {
			builder.setTitle(R.string.menu_deleteall);
			builder.setMessage(R.string.sp_delete_all_NORMAL);
		} else {
			builder.setTitle(R.string.menu_multiselect);
			builder.setMessage(R.string.delete_some);
		}
		
//		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setIconAttribute(android.R.attr.alertDialogIcon);
		builder.setCancelable(true);
        builder.setPositiveButton(android.R.string.yes,
        		new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int which) {
        				delete();
        				Toast.makeText(getActivity(), getString(R.string.delete_toast), Toast.LENGTH_SHORT).show();
        			}
        		});
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
	}

/*	private void setDaysofweek(int mDays) {
		 count selected days 
		int dayCount = 0, days = mDays;
        while (days > 0) {
        	if ((days & 1) == 1) dayCount++;
            days >>= 1;
        }
  
         selected days 
        for (int i = 0; i < 7; i++) {
            if ((mDays & (1 << i)) != 0) {  
                ALSettings.yoil[i] = 1;
                dayCount -= 1;;
            } else {
            	ALSettings.yoil[i] = 0;
            }               	
        }
	}*/
	
	private void modify_ALSettings(String id) {
		Intent iSetAlarm = new Intent();
		iSetAlarm.setClassName(getActivity(), "com.lge.clock.alarmclock.ALSettings");
		
		Cursor cur = null;
		try {

				boolean isUseVolumeControl = CommonUtil.isUseVolumeControl();
				cur = resolver.query(ALProvider.CONTENT_ALARMS_URI,  isUseVolumeControl ? 
						PROJECTION_ARRAYS_2 : PROJECTION_ARRAYS, "_id=" + id, null, null);
				if(cur != null) {
				int hourCol    = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_HOUR);
				int minCol     = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_MINUTES);
				int daysCol    = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_DAYSOFWEEK); 
				int snoozeCol  = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_SNOOZE);
				int toneCol    = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_TONE);
				int vibCol     = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_VIB);
				int enabledCol = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_ENABLED);
				int memoCol    = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_MEMO);
				int puzzleCol  = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_PUZZLE);
/* I3.0 Code [START] */
				int alarmVolume = -1;
				if(isUseVolumeControl) {
					alarmVolume = cur.getColumnIndex(AlarmMeta.COLUMNS.ALARM_VOLUME);
				}
/* I3.0 Code [END] */
			
				if ( cur != null && cur.moveToFirst() ) {
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_ID,			id );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_HOUR,		cur.getString(hourCol) );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_MINUTES,	cur.getString(minCol) );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_DAYSOFWEEK,	cur.getInt(daysCol) );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_SNOOZE,		cur.getString(snoozeCol) );
					
					/*[START] 2012.06.12 suein1209.kim change "on" Uri into default tone Uri*/
					String tempTone = cur.getString(toneCol);
					
					if (tempTone != null && (tempTone.indexOf("content://media") >= 0 || tempTone.equalsIgnoreCase("Off"))){
						Log.d(TAG, "AlarmFragment => create set ringtone uri : "+tempTone);
						iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_TONE,tempTone);
						
					}else{
						
						MediaInfoHolder mediaInfor = CommonUtil.getDefaultRingToneInfo(getActivity(), AlarmDBQueryCondition.SET_ALARM);
						/*if got alarm tone is not ring tone path*/
						if(mediaInfor.mediaURI != null){
							Log.d(TAG, "AlarmFragment => change ("+tempTone+")into ("+mediaInfor.mediaURI.toString()+")");
							tempTone = mediaInfor.mediaURI.toString();
							
						}else{
							Log.e(TAG, "ALSettings => update alarm tone uri is null");
						}//End Of if
						iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_TONE,tempTone);
						
					}//End Of if
					/*[END] 2012.06.12 suein1209.kim change "on" Uri into default tone Uri*/
					
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_VIB,		cur.getString(vibCol) );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_ENABLED,	cur.getString(enabledCol) );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_MEMO,		cur.getString(memoCol) );
					iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_PUZZLE,		cur.getString(puzzleCol) );
/* I3.0 Code [START] */
					if(isUseVolumeControl) {
						iSetAlarm.putExtra( AlarmMeta.COLUMNS.ALARM_VOLUME,		cur.getString(alarmVolume) );
					}
/* I3.0 Code [END] */
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if ( cur != null )
				cur.close();
		}
		
		if ( iSetAlarm != null ) {
			iSetAlarm.setAction("UPDATE");
			startActivity(iSetAlarm);
		}
	}

	/**
	 * Method delete.
	 */
	public void delete() {
		Map.Entry<String, String>temp;
        Set entrys;
        Iterator ii ;
        entrys = storageCheckMaps.entrySet();
        Log.d(TAG,Integer.toString(entrys.size()));
        ii = entrys.iterator();
           
        StringBuffer strIDs = new StringBuffer(INITIAL_BUFF_SIZE);
        strIDs.append("");
          
        NotificationManager nm = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        while(ii.hasNext()) {
            temp = (Map.Entry<String, String>) ii.next();
            
            if ("1".equals(temp.getValue())) {
            	strIDs.append(temp.getKey() + ",");
            	
            	try {
            		nm.cancel( Integer.parseInt(temp.getKey()));
            	} catch ( NumberFormatException e ) {
            		e.printStackTrace();
            	}
            	
            	killOnProcess2(temp.getKey());
            	
            	Log.d(TAG, temp.getValue() + ", " + temp.getKey());
            }    
        }
           
        if ( strIDs.toString().trim().length() > 0 ) {
        	int ch = strIDs.toString().lastIndexOf(',');        

        	String deleteTarget = "_id IN (" + strIDs.toString().substring(0, ch) + ") ";
        	String snooze_deleteTarget = "aid IN (" + strIDs.toString().substring(0, ch) + ") ";
	        Log.d(TAG, "deleteTarget ==" + deleteTarget + "===");
	        Log.d(TAG, "deleteTarget ==" + snooze_deleteTarget + "===");
	        
	        /**
	         * Removes an existing Alarm.  If this alarm is snoozing, disables
	         * snooze.  Sets next alert.
	         */ 
	        getActivity().getContentResolver().delete(ALProvider.CONTENT_ALARMS_URI, deleteTarget, null); 
	        getActivity().getContentResolver().delete(ALProvider.CONTENT_CALCU_URI, snooze_deleteTarget, null);
	              
	        Alarms.setNextAlert(getActivity()); 
	        
	        onResume();
        }    
	}      
	/**
	 * donggeun.kim
	 * case2) during alarm, when alarm delete in delete mode, alarm activity is killed.
	 * @param _id
	 */
	private void killOnProcess2(String id) {
    	Log.d(TAG,"===Delete====_id===>" + id);
    	NotificationManager nm = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    	
    	try {
    		nm.cancel( Integer.parseInt(id) );
    	} catch ( NumberFormatException e ) {
    		e.printStackTrace();
    	}
                	
    	AlarmAlert aa = (AlarmAlert)AlarmAlert.mAlarmSavings.get(id);
    	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection [[
    	if (aa == null ){
    	    return; 
    	}
    	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection ]]
    	aa.forceStop();
    	AlarmAlert.mAlarmSavings.remove(id);
	}
	                               
	   
	//// private class       
//=========== Begin =============================================================
	private class  AlarmListCursorAdapter extends ResourceCursorAdapter 
	{
		private int[] mFromRows;
	    private int[] mToRows;
	    
	    // Just for test 
	    private int mStringConversionColumn = -1;
	    private CursorToStringConverter mCursorToStringConverter;
	    private ViewBinder mViewBinder;
	    private String[] mOriginalFromStrings;
	    private final Map<View, View[]> mHolders = new WeakHashMap<View, View[]>();
		private final AlarmFragment testlist;
		private final Cursor mCursor;
		private AlarmListCursorAdapter(AlarmFragment fragment, int layout, Cursor c, String[] fromStrs, int[] toInts) {
	        super(fragment.getActivity(), layout, c);
	        mToRows = toInts;
	        mOriginalFromStrings = fromStrs;
	        findColumns(fromStrs);
	        testlist = fragment;
	        mCursor = c;
	    }
	    
	    /**
	     * Method newView.
	     * @param context Context
	     * @param cursor Cursor
	     * @param parent ViewGroup
	     * @return View
	     */
	    @Override
	    public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = mFactory.inflate(R.layout.alarm_main_listitem, parent, false);
//            if(mShowDivider){
//	            View divider = (View)view.findViewById(R.id.switch_divider);
//	            divider.setVisibility(View.VISIBLE);
//            }
            ViewHolder holder = new ViewHolder();
            
//            holder.rowLayout = (FrameLayout)view.findViewById(R.id.rowLayout);
            holder.tvMINUTES = (TextView)view.findViewById(R.id.minutes);
            holder.tvHOUR = (TextView)view.findViewById(R.id.hour);
            holder.tvAPM = (TextView)view.findViewById(R.id.apm);
            holder.tvDAYS = (TextView)view.findViewById(R.id.daysofweek);
//            holder.tvGUBUN = (TextView)view.findViewById(R.id.gubun);
			
            holder.eee = (LinearLayout)view.findViewById(R.id.eee);
            /*[START] 2012.02.24 suein1209.kim chage the sliding button*/
            holder.switchSlideBtn = (Switch) view.findViewById(R.id.switchSlideBtn);
//          holder.aa = (LinearLayout)view.findViewById(R.id.abcd);
            /*[END] 2012.02.24 suein1209.kim chage the sliding button*/
            view.setTag(holder);
            
            return view;
        } 

	    /**
	     * Method newDropDownView.
	     * @param context Context
	     * @param cursor Cursor
	     * @param parent ViewGroup
	     * @return View
	     */
	    @Override
	    public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
	        return generateViewHolder(super.newDropDownView(context, cursor, parent));
	    }
	    
	    private static final int VIEW_CNT = 4;

	    private View generateViewHolder(View v) {
	        final int[] viewIDs = mToRows;
	        final int count = viewIDs.length;
	        final View[] holders = new View[VIEW_CNT];

	        for ( int i = 0; i < count; i++ ) {
	        	holders[i] = v.findViewById(viewIDs[i]);
	        }
	         
	        mHolders.put(v, holders);

	        return v;
	    }
	    
        private void updateIndicatorAndAlarm(boolean enabled, String id, int hour, int minutes, Alarms.DaysOfWeek daysOfWeek) {
            // added by essin@lge.ocm 2010.11.29
        	
        	/*[START] 2012.03.29 suein1209.kim, Medic : 5842*/
            // 20101104_mhkwon_QG15889_Touch_tone  [[
//            mTouchSoundHandler.post(playTouchToneThread);
            // 20101104_mhkwon_QG15889_Touch_tone  ]]
            /*[END] 2012.03.29 suein1209.kim, Medic : 5842*/
            if (enabled) {
                storageOnOffMaps.put(id, "1");
            if ( testlist != null )
                testlist.update(id, "1", hour, minutes, daysOfWeek);
            	if(cursorQuery != null && (!cursorQuery.isClosed())) {
                    cursorQuery.requery();
            	}
            } else {
                storageOnOffMaps.put(id, "0");
                if ( testlist != null )
                testlist.update(id, "0", hour, minutes, daysOfWeek);
                if(cursorQuery != null && (!cursorQuery.isClosed())) {
                    cursorQuery.requery();	
                }
                        					
                killOnProcess2(id);
            }
        }
	    
	    private final class ViewHolder {
//	    	private FrameLayout rowLayout;
			
			private TextView tvMINUTES;
			private TextView tvHOUR;
			private TextView tvAPM;
			private TextView tvDAYS;
//			private TextView tvGUBUN;
			
			private LinearLayout eee;
			
			/*[START] 2012.02.24 suein1209.kim chage the sliding button*/
			private Switch switchSlideBtn;
//			private LinearLayout aa;
			/*[END] 2012.02.24 suein1209.kim chage the sliding button*/
		}
	  
	    /**
	     * Method bindView.
	     * @param view View
	     * @param context Context
	     * @param cursor Cursor
	     */
	    @Override
	    public void bindView(View view, Context context, Cursor cursor) {

	    	final Alarms.DaysOfWeek daysOfWeek = new Alarms.DaysOfWeek( cursor.getInt(3) );
	        
	    	// _id = primary key ,  enabled = 'On/Off'  
	    	final String id = Integer.toString(cursor.getInt(0)) ;
	    	//final String enabled = cursor.getString(4); 
	    	final int hour = cursor.getInt(1); 
	    	final int minutes = cursor.getInt(2);
			
	    	final ViewHolder holder = (ViewHolder)view.getTag();
			
	    	final LinearLayout addbuttonLayout = (LinearLayout)view.findViewById(R.id.addbuttonLayout);
	    	addbuttonLayout.setVisibility(View.GONE);
	    	

                boolean is24HourFormat = DateFormat.is24HourFormat(testlist.getActivity());

                /* LGSI_CHANGE_S: Arabic and Farsi number conversion support.
                 * 15/02/12 pradeep.gk@lge.com.
                 * To support arabic and farsi number conversion support.
                 */
                if(CommonUtil.isArabFarsiLanguage()) {
                    if (Integer.toString(minutes).length() == 1) {
                       (holder.tvMINUTES).setText(CommonUtil.convertArabFarsiNum(("0" + Integer.toString(minutes)),false));
                    } else {
                       (holder.tvMINUTES).setText(CommonUtil.convertArabFarsiNum( Integer.toString(minutes),false));
                    }
                    if (is24HourFormat == true) {
                        if (Integer.toString(hour).length() == 1) {
                            (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum(("0" +  Integer.toString(hour)),false));
                        } else {
                            (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum(Integer.toString(hour),false));
                        }
                        (holder.tvAPM).setVisibility(View.GONE);
                    } else {
                        if (hour >= 13 && hour <= 23) {
                            final int hPM = hour - 12;
                            (holder.tvHOUR).setText( CommonUtil.convertArabFarsiNum(Integer.toString(hPM),false));
                        } else if (hour == 0) {
                            (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum("12",false));
                        } else {
                            (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum(Integer.toString(hour),false));
                        }
                        (holder.tvAPM).setVisibility(View.VISIBLE);
                        if (hour >= 0 && hour <= 11) {
                            (holder.tvAPM).setText( R.string.sp_AM_string_NORMAL);
                        } else {
                            (holder.tvAPM).setText( R.string.sp_PM_string_NORMAL);
                        }
                    }
                }
                else {
                   if (Integer.toString(minutes).length() == 1) {
                       (holder.tvMINUTES).setText("0" + Integer.toString(minutes));
                   }else {
                       (holder.tvMINUTES).setText( Integer.toString(minutes));
                }
                /* LGSI_CHANGE_E: Arabic and Farsi number conversion support */
	    	if (is24HourFormat == true) {
	    		if (Integer.toString(hour).length() == 1) {
	    			(holder.tvHOUR).setText("0" +  Integer.toString(hour));
	    		} else {
	    			(holder.tvHOUR).setText(Integer.toString(hour));
	    		}  
				 
	    		(holder.tvAPM).setVisibility(View.GONE);
	    	} else {
	    		if (hour >= 13 && hour <= 23) {
	    			final int hPM = hour - 12;
	    			//[hyunyong.sim] Start Sinario Change when 12 format 
	    			(holder.tvHOUR).setText( Integer.toString(hPM));
	    			//[hyunyong.sim] End Sinario Change when 12 format 
	    		} 
	    		else if (hour == 0) {     
	    			(holder.tvHOUR).setText("12");
	    		} 
	    		else {
	    			//[hyunyong.sim] Start Sinario Change when 12 format 
	    			(holder.tvHOUR).setText(Integer.toString(hour));	
	    			//[hyunyong.sim] End Sinario Change when 12 format 
	    		}     
	    		////////////////////////////////////////////////////////////////////////////////////////	         
	    		(holder.tvAPM).setVisibility(View.VISIBLE);
	    		if (hour >= 0 && hour <= 11) {
	    			(holder.tvAPM).setText( R.string.sp_AM_string_NORMAL);
	    		} else {
	    			(holder.tvAPM).setText( R.string.sp_PM_string_NORMAL);
                       /* LGSI_CHANGE_S: Arabic and Farsi number conversion support.
                        * 15/02/12 pradeep.gk@lge.com.
                        * To support arabic and farsi number conversion support.
                        */
                         }
                       /* LGSI_CHANGE_E: Arabic and Farsi number conversion support */
	        }
		}
	    	//////////////////////////////////////////////////////////////
    			 
	    	(holder.tvDAYS).setText(daysOfWeek.toString(testlist.getActivity()));
	    	
	    	final String enabled = cursor.getString(4);
    		holder.eee.setVisibility(View.VISIBLE);    		
    		
    		holder.switchSlideBtn.setOnCheckedChangeListener(null);
    		/*[START] 2012.02.24 suein1209.kim chage the sliding button*/
    		holder.switchSlideBtn.setChecked("1".equals(enabled));
	    	holder.switchSlideBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
	    		@Override
	    		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
	    			Log.d("suein", "2 =========CompoundButton buttonView, boolean isChecked========== ");
	    			updateIndicatorAndAlarm(isChecked, id, hour, minutes, daysOfWeek);
	    		}
	    	});
	    	
	    	holder.switchSlideBtn.setFocusable(false);
    		
			holder.eee.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					holder.switchSlideBtn.setChecked(!"1".equals(enabled));
				}
			});

			holder.eee.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View arg0, MotionEvent event) {
					// TODO Auto-generated method stub

					if (event != null) {
						int action = event.getAction();

						if (action == MotionEvent.ACTION_UP
								|| action == MotionEvent.ACTION_CANCEL) {
							if (holder.switchSlideBtn.isChecked()) {
								holder.switchSlideBtn.setChecked(false);
							}
						}

					}
					return true;
				}

			});
			
//    		if ("1".equals(enabled)) {
//    			holder.aa.setBackgroundResource(R.drawable.btn_alarm_on_normal);
//    		} else if ("0".equals(enabled)) {
//    			holder.aa.setBackgroundResource(R.drawable.btn_alarm_off_normal);
//    		}
//		  
//    		holder.aa.setOnTouchListener(new OnTouchListener(){
//    			public boolean onTouch(View v, MotionEvent event) {     
//    				Log.d(TAG, "=== On/Off==event.getAction())===>" + event.getAction());
//    				if (event.getAction() == MotionEvent.ACTION_CANCEL) {
//    					if ("0".equals(enabled)) {
//    						v.setBackgroundResource(R.drawable.btn_alarm_off_normal);
//    					} else if ("1".equals(enabled)) {
//    						v.setBackgroundResource(R.drawable.btn_alarm_on_normal);
//    					}
//    					return true;
//    				} 
//						      
//    				if ("0".equals(enabled)) {
//    					switch (event.getAction()) {
//        			  		case MotionEvent.ACTION_DOWN:
//        			  			v.setBackgroundResource(R.drawable.btn_alarm_off_press);
//        			  			return true; 
//									
//							case MotionEvent.ACTION_MOVE:
//								v.setBackgroundResource(R.drawable.btn_alarm_off_press);
//								return true;
//								
//							case MotionEvent.ACTION_UP:       
//								updateIndicatorAndAlarm(true, id, hour, minutes, daysOfWeek);
//								v.setBackgroundResource(R.drawable.btn_alarm_on_normal);
//								return true;
//								
//							default :
//								v.setBackgroundResource(R.drawable.btn_alarm_off_normal);
//								return true;              
//    					}
//    				} else {                     
//    					switch (event.getAction()) {
//        			  		case MotionEvent.ACTION_DOWN:
//        			  			v.setBackgroundResource(R.drawable.btn_alarm_on_pressed);
//								return true; 
//									
//							case MotionEvent.ACTION_MOVE:
//								v.setBackgroundResource(R.drawable.btn_alarm_on_pressed);
//								return true;
//								
//							case MotionEvent.ACTION_UP:       
//								updateIndicatorAndAlarm(false, id, hour, minutes, daysOfWeek) ;         
//								v.setBackgroundResource(R.drawable.btn_alarm_off_normal);
//								return true;
//								
//							default :
//							   	v.setBackgroundResource(R.drawable.btn_alarm_off_normal);
//								return true;   
//    					}      
//    				}
//    			}
//    		});
	    	
	    	/*[END] 2012.02.24 suein1209.kim chage the sliding button*/
			  
	    	final CheckedTextView checkView = (CheckedTextView)view.findViewById(R.id.CheckBox);
    		checkView.setVisibility(View.GONE); 
	    }
	  
	    // 20101019_mhkwon_Block multi touch [[chk
	   /* Handler BlockMultiTouchHandler = new Handler();
	    Runnable BlockMultiTouchThread = new Runnable() {
	    	public void run() {
	    		BlockMultiTouchFlag = false;  
	    	};
	    };*/
	    //20101019_mhkwon_Block multi touch ]]
	  
	    /**
	     * Returns the {@link ViewBinder} used to bind data to views.
	     *
	     * @return a ViewBinder or null if the binder does not exist
	     *
	     * @see #bindView(android.view.View, android.content.Context, android.database.Cursor)
	     * @see #setViewBinder(android.widget.AlarmListCursorAdapter.ViewBinder)
	     */
	    public ViewBinder getViewBinder() {
	    	return mViewBinder;
	    }

	    /**
	     * Sets the binder used to bind data to views.
	     *
	     * @param viewBinder the binder used to bind data to views, can be null to
	     *        remove the existing binder
	     *
	     * @see #bindView(android.view.View, android.content.Context, android.database.Cursor)
	     * @see #getViewBinder()
	     */
	    public void setViewBinder(ViewBinder viewBinder) {
	    	mViewBinder = viewBinder;
	    }

	    /**
	     * Called by bindView() to set the image for an ImageView but only if
	     * there is no existing ViewBinder or if the existing ViewBinder cannot
	     * handle binding to an ImageView.
	     *
	     * By default, the value will be treated as an image resource. If the
	     * value cannot be used as an image resource, the value is used as an
	     * image Uri.
	     *
	     * Intended to be overridden by Adapters that need to filter strings
	     * retrieved from the database.
	     *
	     * @param v ImageView to receive an image
	     * @param value the value retrieved from the cursor
	     */
	    public void setViewImage(ImageView v, String value) {
	    	try {
	    		v.setImageResource(Integer.parseInt(value));
	    	} catch (NumberFormatException nfe) {
	    		v.setImageURI(Uri.parse(value));
	    		nfe.printStackTrace();
	    	}
	    }

	    /**
	     * Called by bindView() to set the text for a TextView but only if
	     * there is no existing ViewBinder or if the existing ViewBinder cannot
	     * handle binding to an TextView.
	     *
	     * Intended to be overridden by Adapters that need to filter strings
	     * retrieved from the database.
	     * 
	     * @param v TextView to receive text
	     * @param text the text to be set for the TextView
	     */    
	    public void setViewText(TextView v, String text) {
	    	v.setText(text);
	    }

	    /**
	     * Return the index of the column used to get a String representation
	     * of the Cursor.
	     *
	     * @return a valid index in the current Cursor or -1
	     *
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     * @see #setStringConversionColumn(int) 
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter)
	     * @see #getCursorToStringConverter()
	     */
	    public int getStringConversionColumn() {
	    	return mStringConversionColumn;
	    }

	    /**
	     * Defines the index of the column in the Cursor used to get a String
	     * representation of that Cursor. The column is used to convert the
	     * Cursor to a String only when the current CursorToStringConverter
	     * is null.
	     *
	     * @param stringConversionColumn a valid index in the current Cursor or -1 to use the default
	     *        conversion mechanism
	     *
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     * @see #getStringConversionColumn()
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter)
	     * @see #getCursorToStringConverter()
	     */
	    public void setStringConversionColumn(int stringConversionColumn) {
	    	mStringConversionColumn = stringConversionColumn;
	    }

	    /**
	     * Returns the converter used to convert the filtering Cursor
	     * into a String.
	     *
	     * @return null if the converter does not exist or an instance of
	     *         {@link android.widget.AlarmListCursorAdapter.CursorToStringConverter}
	     *
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter)
	     * @see #getStringConversionColumn()
	     * @see #setStringConversionColumn(int)
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     */
	    public CursorToStringConverter getCursorToStringConverter() {
	    	return mCursorToStringConverter;
	    }

	    /**
	     * Sets the converter  used to convert the filtering Cursor
	     * into a String.
	     *
	     * @param cursorToStringConverter the Cursor to String converter, or
	     *        null to remove the converter
	     *
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter) 
	     * @see #getStringConversionColumn()
	     * @see #setStringConversionColumn(int)
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     */
	    public void setCursorToStringConverter(CursorToStringConverter cursorToStringConverter) {
	    	mCursorToStringConverter = cursorToStringConverter;
	    }

	    /**
	     * Returns a CharSequence representation of the specified Cursor as defined
	     * by the current CursorToStringConverter. If no CursorToStringConverter
	     * has been set, the String conversion column is used instead. If the
	     * conversion column is -1, the returned String is empty if the cursor
	     * is null or Cursor.toString().
	     *
	     * @param cursor the Cursor to convert to a CharSequence
	     *
	    
	     * @return a non-null CharSequence representing the cursor */
	    @Override
	    public CharSequence convertToString(Cursor cursor) {
	    	if (mCursorToStringConverter != null) {
	    		return mCursorToStringConverter.convertToString(cursor);
	    	} else if (mStringConversionColumn > -1) {
	    		return cursor.getString(mStringConversionColumn);
	    	}

	    	return super.convertToString(cursor);
	    }
     
	    /**
	     * Create a map from an array of strings to an array of column-id integers in mCursor.
	     * If mCursor is null, the array will be discarded.
	     * 
	     * @param from the Strings naming the columns of interest
	     */
	    private void findColumns(String[] fromCols) {
            try {
                Cursor mCursor = getCursor();
                if (mCursor != null) {
                    int count = fromCols.length;
                    if (mFromRows == null || mFromRows.length != count) {
                        mFromRows = new int[count];
                    }
                    for (int i = 0; i < count; i++) {
                        mFromRows[i] = mCursor.getColumnIndexOrThrow(fromCols[i]);
                    }
                } else {
                    mFromRows = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                if (mCursor != null) {
//                    mCursor.close();
//                }
            }
        }

	    /**
	     * Method changeCursor.
	     * @param c Cursor
	     */
	    @Override
	    public void changeCursor(Cursor c) {
	    	super.changeCursor(c);
	    	// rescan columns in case cursor layout is different
	    	findColumns(mOriginalFromStrings);
	    }
	                     
	    /**
	     * Change the cursor and change the column-to-view mappings at the same time.
	     *  
	     * @param c The database cursor.  Can be null if the cursor is not available yet.
	    
	    
	     * @param froms String[]
	     * @param tos int[]
	     */
	    public void changeCursorAndColumns(Cursor c, String[] froms, int[] tos) {
	    	mOriginalFromStrings = froms;
	    	mToRows = tos;
	    	super.changeCursor(c);
	    	findColumns(mOriginalFromStrings);
	    }
	}
	//============ class End==========
     
    /**
     *  row long press
     * @param menu ContextMenu
     * @param view View
     * @param menuInfo ContextMenuInfo
     * @see android.view.View$OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
     */
	@Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
		/*[START]2012.01.06 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #118379, Medic : 2971*/
        AdapterView.AdapterContextMenuInfo info = null;
        try {
        	info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        }
        catch(ClassCastException e) {
        	Log.e(TAG, "Exception : "+e.getMessage());
            return;
        } //End of try
        
        menu.setHeaderTitle(R.string.alarm);
        menu.add(Menu.NONE, R.id.delete_alarm, Menu.NONE, getResources().getString(R.string.menu_multiselect));
		
//        // Inflate the menu from xml.
//        getActivity().getMenuInflater().inflate(R.menu.context_menu, menu);
//        
//        // Inflate the custom view and set each TextView's text.
//        final View v = mFactory.inflate(R.layout.alarm_context_menu_header, null);
//        TextView textView = (TextView) v.findViewById(R.id.header_title);
//        textView.setText( getText(R.string.alarm).toString() );// alert_title
//         
//        // Set the custom view on the menu.
//        menu.setHeaderView(v);
        
        /*[END]2012.01.06 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #118379, Medic : 2971*/
    }
    
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setHasOptionsMenu(true);
		
		//checkShowDivier();
		
		mContext = getActivity();
		
		resolver = mContext.getContentResolver();
		SharedPreferences prefs = mContext.getSharedPreferences("com.lge.clock_preferences", 0);

		String sideButtons = prefs.getString("volume_button_setting", "1");
		/** 
		 * Side button & Voip state setting
		 */
		if ("ZERO".equalsIgnoreCase(sideButtons)) {
			prefs.edit().putString("volume_button_setting", "2").commit();
			prefs.edit().putString("voip_state", "0").commit();
			
            Log.d(TAG, "===sideButtons====>" + sideButtons );
            legalToneSetting();
        }

		// 20101014_mhkwon_SE10016_ALStart_ANR [[
		Handler setNextAlertHandler = new Handler();
		if ( setNextAlertThread != null )
			setNextAlertHandler.postDelayed(setNextAlertThread, 0);
		// 20101014_mhkwon_SE10016_ALStart_ANR ]]
		
//		//sunghun.an@lge.com Common : Gesture Guide Pop up  [START]
//		pref = getActivity().getSharedPreferences("gesture_guide", 0);
//		mGestureGuide = pref.getBoolean("gesture_guide",mGestureGuide);
//		Log.e(TAG,"GestureGuide = " + mGestureGuide+", isFacingSensorSupported : "+isFacingSensorSupported());
//		if(mGestureGuide == false && isFacingSensorSupported())
//		{
//			showGestureGuide(mContext);
//		
//		}
//		//sunghun.an@lge.com Common : Gesture Guide Pop up  [END]
	}

	// onCreateContextMenu
	/**
	 * Method onContextItemSelected.
	 * @param item MenuItem
	 * @return boolean
	 */
	@Override
    public boolean onContextItemSelected(final MenuItem item) {
        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        final int id = (int) info.id;
        
        switch (item.getItemId()) {
            case R.id.delete_alarm:
            	confirmDeleteDialog(id);
            	break;
            	
            default:
                break;
        }
        
        return super.onContextItemSelected(item);
    }
     
    // onCreateContextMenu 
	private void confirmDeleteDialog(final int id) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        
        builder.setTitle(getString(R.string.menu_multiselect));
        builder.setMessage(getResources().getString(R.string.delete_alarm_confirm));
        
//        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setIconAttribute(android.R.attr.alertDialogIcon);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.timer_set_alerttone_ok,                     
        		new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int which) {
        				deleteOnlyOne(Integer.toString(id));
        				Toast.makeText(getActivity(), getString(R.string.delete_toast), Toast.LENGTH_SHORT).show();
        			}
        		});
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    } 
    
	/** 
	 * confirmDeleteDialog
	 * @param id String
	 */
	public void deleteOnlyOne(String id) {
        StringBuffer strIDs = new StringBuffer(INITIAL_BUFF_SIZE);
        strIDs.append(id);
        
        NotificationManager nm = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        
        try {
        	nm.cancel( Integer.parseInt(id) );
        } catch ( NumberFormatException e ) {
        	e.printStackTrace();
        }
    	   
        if ( strIDs.toString().trim().length() > 0 ) {
        	String deleteTarget = "_id IN (" +  strIDs.toString() + ") ";
        	String snoozeDeleteTarget = "aid IN (" +  strIDs.toString() + ") ";
	        
	        /**
	         * Removes an existing Alarm.  If this alarm is snoozing, disables
	         * snooze.  Sets next alert.
	         */
	        getActivity().getContentResolver().delete(ALProvider.CONTENT_ALARMS_URI, deleteTarget, null);
	        getActivity().getContentResolver().delete(ALProvider.CONTENT_CALCU_URI, snoozeDeleteTarget, null);
	                   
	        Alarms.setNextAlert(getActivity());
	        killOnProcess2(id);
	        
	        onResume();
        }
	}
	
	private static final String[] INTERNAL_COLUMNS = new String[] {
	     android.provider.BaseColumns._ID,
	     android.provider.MediaStore.MediaColumns.TITLE,
	     "\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
	     android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
	};
	
	private void legalToneSetting() {
    	Log.d(TAG, "===legalToneSetting====");
    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_ALARM);
	    if (alert == null) {
        	Settings.System.putString(resolver, Settings.System.ALARM_ALERT, null);
        	ContentValues values = new ContentValues(1);
        	values.put("tone", "Off" );
        	resolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + 1 , null);
	    } else { 
	    	int i = 1;
            boolean tag = false;
            String defaulttone = "";
	    	
	    	Cursor cur = null;
	    	try {
	    		cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
               			"is_alarm = 1", null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
	    		if ( cur != null && cur.moveToFirst() ) {
	    	 		do {
	    	 			// Get the field values
	    	 			Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
	    	            if (uri1.toString().equalsIgnoreCase(alert.toString())) {       
	    	            	Settings.System.putString(resolver, Settings.System.ALARM_ALERT, uri1.toString()); 
	    	             	    
	    	             	ContentValues values = new ContentValues(1);
	    	             	values.put("tone", uri1.toString() );
	    	             	resolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + 1 , null);
	    	             	tag = true; 
		    	            break;   
	    	            }
	    	            if (i == 4) {
	    	            	defaulttone = uri1.toString();
	    	            }
	    	            i++;
	    	 		} while (cur.moveToNext());
	    	 	}
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    	} finally {
	    		if ( cur != null )
	    			cur.close();
	    	}

	    	if (tag == false) {
	    		ContentValues values = new ContentValues(1);
             	values.put("tone", defaulttone );
	    		if ( resolver != null ) {
	    			Settings.System.putString(resolver, Settings.System.ALARM_ALERT, defaulttone ); 
	    			resolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + 1 , null);
	    		}
    	 	}
	    }  
	}
	
    //BASICPKG_S AlarmClock [sungtan.back@lge.com 110314]
    private void setAlarm(String strID) {
		Intent iSetAlarm = new Intent();
		iSetAlarm.setClassName(getActivity(), "com.lge.clock.alarmclock.ALSettings");
        iSetAlarm.setAction("INSERT");
        startActivity(iSetAlarm);
    }
    //BASICPKG_E AlarmClock

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
		if( cursorQuery != null) {
			cursorQuery.close();
		}        
    }

//    /**
//     * 2012.01.27 suein1209.kim
//     * is facing sensor supported ?
//     * @return
//     */
//    private boolean isFacingSensorSupported(){
//    	
//    	SensorManager sensorManager = (SensorManager) ((Activity)mContext).getSystemService(Context.SENSOR_SERVICE);    
//    	// get all sensors of all types         
//    	List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL); 
//    	
//    	for(int i=0; i<sensorList.size(); i++){
//    		
//    		if(sensorList.get(i).getType()== LGSensor.TYPE_SENSOR_LGE_GESTURE_FACING){
//    			return true;
//    		} //End Of if
//    	} //End Of for i
//    	
//    	return false;
//    } //End Of Method 
    
//  //sunghun.an@lge.com Common : Gesture Guide Pop up  [START]
//  	private void showGestureGuide(Context context)
//      {
//  		((Activity)mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//  		LayoutInflater inflater = (LayoutInflater)((Activity)mContext).getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//  		View layout = inflater.inflate(R.layout.popup_gesture_guide, null);
//
//  		final ImageView mImageView = (ImageView) layout.findViewById(R.id.gestureImage);
//  		mImageView.setImageDrawable(getResources().getDrawable(R.drawable.gesture_anim));
//  		mAnimation = (AnimationDrawable) mImageView.getDrawable();
//  		
//  		TextView gtext = (TextView) layout.findViewById(R.id.gestureText);
//  		gtext.setText(R.string.sp_gesture_info_alarm_NORMAL);
//
//  		check= (CheckBox) layout.findViewById(R.id.GuideCheck);
//  		check.setText(R.string.sp_do_not_show_this_again_NORMAL);
//
//
//  		gestureGuideDlg= new AlertDialog.Builder(context)
//  		.setTitle(R.string.sp_gesture_guide_title_NORMAL)
//  		.setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener()
//  		{
//  			public void onClick(DialogInterface dialog, int which) {
//  				if(check.isChecked()) 
//  				{
//  					Log.e(TAG,"Check OK");
//  					mGestureGuide=true;
//  					SharedPreferences.Editor edit = pref.edit();
//
//  					edit.putBoolean("gesture_guide", mGestureGuide);
//
//  					edit.commit();
//  				}
//  				
//  				gestureDlgDismiss();
//
//  				
//  			}
//  		})
//  		.setNegativeButton(R.string.sp_gesture_settings_NORMAL, new DialogInterface.OnClickListener() {
//  			public void onClick(DialogInterface dialog, int which) {
//  				Log.e(TAG,"Gesture Setting");
//
//				Intent intent = new Intent(Intent.ACTION_VIEW);
//				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//
//				try {
//					intent.setClassName("com.android.settings", "com.android.settings.Settings$GestureSettingsActivity");
//					startActivity(intent);
//				} catch (ActivityNotFoundException e) {
//					Log.e(TAG, "Exception : AlarmFragment -> showGestureGuide : " + e.getMessage());
//				} //End Of try
//
//				gestureDlgDismiss();
//  				
//  			}
//  		})
//  		.setOnCancelListener(new DialogInterface.OnCancelListener() {
//              @Override
//              public void onCancel(DialogInterface dialog) {
//  				gestureDlgDismiss();
//              }
//          })
//  		.setView(layout)
//  		.show();
//
//
//  		new Handler().postDelayed(new Runnable()		 
//  		{			  
//  			@Override
//  			public void run(){
//  				if(mAnimation != null)
//  				{
//  					mAnimation.start(); 	
//  				}
//  			}	   
//  		}, 1000); 
//     	
//      }
//
//  	private void gestureDlgDismiss()
//  	{
//  		((Activity)mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 
//  		if (mAnimation != null && mAnimation.isRunning()) {
//  			mAnimation.stop();
//  			mAnimation = null;
//  		}	
//  		if(gestureGuideDlg != null)
//  		{
//  			gestureGuideDlg.dismiss();
//  			gestureGuideDlg=null;
//  		}
//  	}
//  	//sunghun.an@lge.com Common : Gesture Guide Pop up  [END]
    
//    private void checkShowDivier(){
//    	mShowDivider = (CommonUtil.getBuildOperator() == OPERATOR.VZW);
//    }
    
}